from LogManager import log_output
import os

torch_python_environ = '/home/dingyueprp/.conda/envs/xzth38/bin/python'
tf_python_environ = '/usr/local/anaconda3/envs/chtf/bin/python'

try:
    f = open('__file_lock', 'rt')
    print('Process still running! Please wait for the previous process to finish!')
    exit(-1)
except Exception:
    with open('__file_lock', 'wt') as fo:
        fo.write('Processing...')

try:
    print('Main: Fetching files')
    result = os.system(f'{torch_python_environ} FetchFile.py')
    print(result)
    if result != 0:
        raise ValueError("Main: 在获取文件时出现错误")
    print('Main: Finished.')
    print('Main: Start preprocessing...') 
    try:
        os.remove('BPRMF/model_dat/dataset.pkl')   
        os.remove('BPRMF/model_dat/model.pkl')
        os.remove('ICF/model_dat/W.pkl')
        os.remove('UCF/model_dat/W.pkl')
    except Exception:
        pass
    result = os.system(f'{torch_python_environ} preprocess.py')
    print(result)
    if result != 0:
        raise ValueError("Main: 在预处理时出现错误")
    print('Main: Finished.')

    print('Main: Start Fine Recommendation...')
    result = os.system(f'{tf_python_environ} AttenConvFM.py')
    print(result)
    if result != 0:
        raise ValueError("Main: 在AFM推荐时出现错误")
    print('Main: Finished.')

    print('Main: Final Output...')
    result = os.system(f'{torch_python_environ} FinalOutput.py')
    print(result)
    if result != 0:
        raise ValueError("Main: 在输出数据库时出现错误")
    print('Main: Finished.')
except Exception as err:
    log_output(f'Main: {str(err)}')
    log_output(f'出现错误：{str(err)}', send_status=True)
finally:
    os.remove('__file_lock')
